import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from common.helper import Helper
import json,requests


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "人保寿险关爱心脑血管疾病保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(18, 61)],
            # 性别
            "gender": ["M"],
            # 保险期间
            "expire": ["1年"],
            # 交费类型
            "payType": ["年交"],
            # 特定心脑血管重大疾病
            "majorDisease": ["100000"],
            # 特定心脑血管轻症疾病
            "slightDisease": ["0", "20000"],

        }
        for v in product(plan["year"], plan["gender"], plan["expire"], plan["payType"], plan["majorDisease"],
                         plan["slightDisease"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"header": {"transRefGUID": "1231234342356767878", "transDate": "2017-8-14", "transTime": "11:29:00",
                           "businessType": "001"}, "body": {"combCode": "GAXNXGJBBX", "policyType": "1",
                                                            "inputFactors": {"age": dt["year"], "sex": "M", "insuYear": "1Y",
                                                                             "amnt": "10", "FJDQSX": "2",
                                                                             "birth": "{0}-01-01".format( str(2020-int(dt["year"]))),
                                                                             "combcode": "GAXNXGJBBX", "organid": "-1"},
                                                            "addRisks": [] if dt["slightDisease"] == "0" else [{"riskCode":70939,"addRiskAmnt":2}]}}

        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and r.json()["success"]:
            if dt["slightDisease"] == "0":

                price = Helper.decimalParse( r.json()["data"]["mainPrem"] )
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
            else:
                price = Helper.decimalParse(r.json()["data"]["prem"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }

            self.mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格数据失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson( dt )
